﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BusLib
{
    public partial class Stop_Time
    {
        public IEnumerable<Stop_Time> GetNextStops()
        {
            if (Trip.Stop_Times.Count == 0)
                return new List<Stop_Time>(); // No stops on this trip

            if (Trip.Stop_Times.Last() == this)
                return new List<Stop_Time>(); // This was the last stop

            return Trip.Stop_Times.SkipWhile(st => st != this);
        }

        public Stop_Time GetNextStop()
        {
            IEnumerable<Stop_Time> nextStops = GetNextStops();

            if (nextStops.Count() == 0)
                return null;
            else
                return nextStops.First();
        }

        static int submitCount = 0;

        static TimeSpan myTimeParse(string s)
        {
            bool afterMidnight = false;
            string hourStr = s.Split(':')[0];
            int hour = int.Parse(hourStr);
            if (hour >= 24)
            {
                afterMidnight = true;

                hour -= 24;
                s = hour.ToString() + s.Substring(2);
            }
            TimeSpan t = TimeSpan.Parse(s);

            if (afterMidnight)
            {
                t = t.Add(TimeSpan.FromDays(1));
            }

            return t;
        }

        static public Stop_Time ImportCSV(string line)
        {
            Stop_Time time = null;
            string[] fields = line.Split(',');

            if (fields[0] != "trip_id")
            {
                time = new Stop_Time();

                time.trip_id = int.Parse(fields[0]);
                time.arrival_time = myTimeParse(fields[1]);
                time.departure_time = myTimeParse(fields[2]);
                time.stop_id = int.Parse(fields[3]);
                time.stop_sequence = int.Parse(fields[4]);
                time.stop_headsign = fields[5];
                if (fields[6] != "")
                {
                    time.pickup_type = int.Parse(fields[6]);
                }
                if (fields[7] != "")
                {
                    time.drop_off_type = int.Parse(fields[7]);
                }
                if (fields[8] != "")
                {
                    time.shape_dist_travelled = double.Parse(fields[8]);
                }

                BusLibDataContext.db.Stop_Times.InsertOnSubmit(time);
                if (++submitCount > 1000)
                {
                    BusLibDataContext.db.SubmitChanges();
                    submitCount = 0;
                }
            }
            return time;
        }
    }
}
